package com.lucy.rabc.controller;

import cn.hutool.core.lang.Validator;
import com.lucy.common.domain.ResponseDTO;
import com.lucy.rabc.entity.SysRole;
import com.lucy.rabc.entity.SysUser;
import com.lucy.rabc.params.GrantParams;
import com.lucy.rabc.service.SysMenuService;
import com.lucy.rabc.service.SysRoleService;
import com.lucy.rabc.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author kindear
 * 授权管理控制器
 */
@Slf4j
@RestController
@RequestMapping("system")
@Api(tags = "授权管理")
public class GrantController {
    @Autowired
    SysUserService userService;

    @Autowired
    SysMenuService menuService;

    @Autowired
    SysRoleService roleService;

    @PostMapping("/privilege/grant")
    @ApiOperation(value = "授权",notes = "覆盖")
    public ResponseDTO<Object> grantBatch(@RequestBody @Validated GrantParams params){
        // 批量获取用户
        List<Long> userIds = params.getUserIds();
        List<SysUser> users = userService.getByIdBatch(userIds);
        //批量获取角色
        List<Long> roleIds = params.getRoleIds();
        List<SysRole> roles = roleService.getByIdBatch(roleIds);
        //遍历更新用户
        Set<SysRole> roleSet = new HashSet<>(roles);
        users = users.stream().peek(ele->{
            //ele.getRoles().addAll(roles);
            ele.setRoles(new HashSet<>(roleSet));
        }).collect(Collectors.toList());
        return ResponseDTO.succData(
                userService.batchUpdate(users)
        );
    }

    @PostMapping("/privilege/cancel")
    @ApiOperation(value = "取消授权",notes = "")
    public ResponseDTO<Object> cancelBatch(@RequestBody @Validated GrantParams params){
        // 批量获取用户
        List<Long> userIds = params.getUserIds();
        List<SysUser> users = userService.getByIdBatch(userIds);
        //批量获取角色
        List<Long> roleIds = params.getRoleIds();

        List<SysRole> roles = roleService.getByIdBatch(roleIds);
        //遍历更新用户(移除)
        users = users.stream().peek(ele->{
            roles.forEach(ele.getRoles()::remove);
        }).collect(Collectors.toList());
        return ResponseDTO.succData(
                userService.batchUpdate(users)
        );
    }
}
